<template>
  <div>
    <div class="operator">
      <n-button type="primary" @click="addUser">添加用户</n-button>
    </div>
    <n-data-table
      :loading="tableLoading"
      :columns="columns"
      :data="data"
      :pagination="pagination"
      :single-line="false"
    />
    <n-modal
      :style="{ width: '500px' }"
      v-model:show="showModal"
      class="custom-card"
      preset="card"
      :title="update ? '修改用户信息' : '添加用户信息'"
      size="huge"
      :bordered="false"
      :segmented="false"
    >
      <template #header-extra> </template>
      <n-flex>
        <n-form
          :model="form"
          label-placement="left"
          label-width="auto"
          :style="{ width: '100%' }"
        >
          <n-form-item label="工号" required>
            <n-input
              v-model:value="form.jobNumber"
              placeholder="请输入工号(同为默认密码)"
              :allow-input="onlyAllow"
            />
          </n-form-item>
          <n-form-item label="密码" v-if="update">
            <n-input
              v-model:value="form.password"
              placeholder="请输入密码"
              :allow-input="onlyAllow"
            />
          </n-form-item>
          <n-form-item label="姓名" required>
            <n-input v-model:value="form.userName" placeholder="请输入姓名" />
          </n-form-item>
          <n-form-item label="性别">
            <n-select v-model:value="form.sex" :options="options.sex" />
          </n-form-item>
          <n-form-item label="岗位" required>
            <n-select v-model:value="form.post" :options="options.post" />
          </n-form-item>
          <n-form-item label="部门">
            <n-select
              v-model:value="form.department"
              :options="options.department"
            />
          </n-form-item>
          <n-form-item label="电话">
            <n-input v-model:value="form.phone" placeholder="请输入电话" />
          </n-form-item>
          <n-form-item label="邮箱">
            <n-input v-model:value="form.email" placeholder="请输入邮箱" />
          </n-form-item>
          <n-form-item label="权限" required>
            <n-checkbox-group v-model:value="form.jurisdiction">
              <n-space item-style="display: flex;">
                <n-checkbox
                  :value="value"
                  :label="key"
                  v-for="(key, value) in options.jurisdiction"
                  :key="key"
                />
              </n-space>
            </n-checkbox-group>
          </n-form-item>
        </n-form>
      </n-flex>
      <template #footer>
        <n-flex justify="end">
          <n-button @click="showModal = false">取消</n-button>
          <n-button :loading="submitLoading" type="primary" @click="Summit()"
            >确定</n-button
          >
        </n-flex>
      </template>
    </n-modal>
  </div>
</template>
<script setup>
import { NButton, NPopconfirm, NSpace, NTag } from "naive-ui";
import {
  getDepartment,
  addUserInfo,
  getUserList,
  updateUserInfo,
  delUserInfo,
} from "@/api";
import Store from "@/stores";
const store = Store();
const showModal = ref(false);
const submitLoading = ref(false);
const tableLoading = ref(false);
const update = ref(false);
const form = ref({});
const onlyAllow = (value) => !value || /^[a-zA-Z0-9]+$/.test(value);
const options = ref({
  sex: [
    {
      value: "M",
      label: "男",
    },
    {
      value: "W",
      label: "女",
    },
  ],
  jurisdiction: {
    1: "工作管理",
    2: "车辆管理",
    3: "地铁摄像头",
    4: "用户管理",
    5: "部门管理",
  },
  // 人事，检修，普通员工和管理
  post: [
    {
      value: 1,
      label: "普通员工",
    },
    {
      value: 2,
      label: "检修",
    },
    {
      value: 3,
      label: "人事",
    },
    {
      value: 4,
      label: "管理",
    },
    {
      value: 5,
      label: "司机",
    },
  ],
  // 部门
  department: [],
});
const columns = [
  {
    title: "工号",
    key: "jobNumber",
  },
  {
    title: "姓名",
    key: "userName",
    render: (item) => {
      let arr = [h("span", item.userName)];
      if (item.jobNumber == store.userInfo.jobNumber) {
        arr.push(h(NTag, { size: "small", type: "success" }, "当前登录"));
      }
      return h(NSpace, arr);
    },
  },
  {
    title: "性别",
    key: "sex",
    render: (item) => {
      return h(
        "span",
        options.value.sex?.find((v) => v.value == item.department)?.label
      );
    },
  },
  {
    title: "岗位",
    key: "post",
    render: (item) => {
      return h(
        "span",
        options.value.post?.find((v) => v.value * 1 == item.post * 1)?.label
      );
    },
  },
  {
    title: "部门",
    key: "department",
    render: (item) => {
      return h(
        "span",
        options.value.department?.find(
          (v) => v.value * 1 == item.department * 1
        )?.label
      );
    },
  },
  {
    title: "电话",
    key: "phone",
  },
  {
    title: "邮箱",
    key: "email",
  },
  {
    title: "权限",
    key: "jurisdiction",
    render(item) {
      return h(
        NSpace,
        item.jurisdiction.map((item) =>
          h(
            NTag,
            { size: "small", type: "info" },
            options.value.jurisdiction[item]
          )
        )
      );
    },
  },
  {
    title: "操作",
    key: "jurisdiction",
    width: 150,
    render(item) {
      return [
        h(
          NButton,
          {
            type: "info",
            quaternary: true,
            size: "small",
            disabled:
              item.jobNumber == "000" ||
              store.userInfo.jobNumber == item.jobNumber,
            onClick: () => {
              // console.log(item)
              update.value = true;
              form.value = JSON.parse(
                JSON.stringify(Object.assign(item, { _id: item._id }))
              );
              showModal.value = true;
            },
          },
          { default: () => "修改" }
        ),
        h(
          NPopconfirm,
          {
            onPositiveClick: () => {
              console.log(item);
              delUserInfo({ _id: item._id }).then((res) => {
                if (res.code != 200) return $message.error(res.message);
                $message.success(res.message);
                getUsers();
              });
            },
          },
          {
            trigger: () =>
              h(
                NButton,
                {
                  disabled:
                    item.jobNumber == "000" ||
                    store.userInfo.jobNumber == item.jobNumber,
                  type: "error",
                  quaternary: true,
                  size: "small",
                },
                { default: () => "删除" }
              ),
            default: () => "确认删除",
          }
        ),
      ];
    },
  },
];
const data = ref([]);
const pagination = {
  showSizePicker: true,
  pageSizes: [10, 30, 50, 100], //可切换的 每页条数
};
function addUser(params) {
  showModal.value = true;
  update.value = false;
  form.value = {};
}
// 获取部门列表
getDepartmentList();
function getDepartmentList() {
  getDepartment().then((res) => {
    if (res.code != 200) return $message.error(res.message);
    // console.log(res);

    options.value.department = res.data.map((item) => {
      return {
        value: item.number,
        label: item.name,
      };
    });
  });
}
// 查询人员列表
getUsers();
function getUsers() {
  tableLoading.value = true;
  getUserList().then((res) => {
    tableLoading.value = false;
    if (res.code != 200) return $message.error(res.message);
    // console.log(res);
    data.value = res.data;
  });
}
// 添加人员 or 更新人员信息
function Summit() {
  const user = JSON.parse(JSON.stringify(form.value));
  if (!user.jobNumber) return $message.warning("请输入工号");
  if (!user.userName) return $message.warning("请输入姓名");
  if (!user.post) return $message.warning("请选择岗位");
  // 中国手机号(严谨), 根据工信部2019年最新公布的手机号段
  const phone =
    /^(?:(?:\+|00)86)?1(?:(?:3[\d])|(?:4[5-7|9])|(?:5[0-3|5-9])|(?:6[5-7])|(?:7[0-8])|(?:8[\d])|(?:9[1|8|9]))\d{8}$/;
  if (user.phone && !phone.test(user.phone))
    return $message.warning("请输入正确的手机号");
  // 邮箱地址(email)
  const email =
    /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;
  if (user.email && !email.test(user.email))
    return $message.warning("请输入正确的邮箱");
  if (!user.jurisdiction?.length) return $message.warning("请选择人员权限");
  console.log(user);
  const submitMethod = update.value ? updateUserInfo : addUserInfo;
  submitLoading.value = true;
  submitMethod(user).then((res) => {
    submitLoading.value = false;
    if (res.code != 200) return $message.error(res.message);
    $message.success(res.message);
    showModal.value = false;
    getUsers();
  });
}
</script>

<style lang="less" scoped>
.operator {
  margin-bottom: 20px;
}
</style>
